package com.rt.easyjava.base.biz1.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.base.Strings;
import com.rt.easyjava.base.biz1.bean.TmptBaseFileBiz;
import com.rt.easyjava.base.biz1.dto.TmptBaseFileBizDto;
import com.rt.easyjava.base.biz1.mapper.TmptBaseFileBizMapper;
import com.rt.easyjava.base.biz1.service.impl.base.TmptBaseFileServiceImpl;
import com.rt.easyjava.base.biz1.service.intf.TmptBaseFileBizService;
import com.rt.easyjava.base.utils.DfsService;
import com.rt.easyjava.common.base.Result;
import com.rt.easyjava.common.config.dozer.MyMapper;
import com.rt.easyjava.common.utils.others.DateTool;
import com.rt.easyjava.common.utils.others.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 服务实现类
 *
 * @author wuxiaoyong
 * @since 2020-11-18
 */
@Slf4j
@Service(value = "tmptBaseFileService")
@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
public class TmptBaseFileBizServiceImpl extends TmptBaseFileServiceImpl implements TmptBaseFileBizService {
    @Resource
    private MyMapper mapper;
    @Resource
    private TmptBaseFileBizMapper tmptBaseFileBizMapper;

    @Resource
    private DfsService dfsService;


    // ==================================================================================
    // ========== 以下使用的是 Mybatis-plus 实现, 适合单表操作 ==============================
    // ==================================================================================

    /**
     * create a object
     *
     * @param tmptBaseFileBizDto
     * @return
     */
    @Override
    public Result<TmptBaseFileBizDto> create(TmptBaseFileBizDto tmptBaseFileBizDto) {
        return super.create(tmptBaseFileBizDto);
    }

    /**
     * update a object by Id
     *
     * @param tmptBaseFileBizDto
     * @param updateWrapper
     * @return
     */
    @Override
    public Result<TmptBaseFileBizDto> update(TmptBaseFileBizDto tmptBaseFileBizDto, UpdateWrapper updateWrapper) {
        return super.update(tmptBaseFileBizDto, updateWrapper);
    }

    /**
     * 分页 (无合计功能)
     *
     * @param page
     * @param queryWrapper
     * @return
     */
    public Result<TmptBaseFileBizDto> page(Page<TmptBaseFileBiz> page, QueryWrapper<TmptBaseFileBiz> queryWrapper) {
        return super.page(page, queryWrapper);
    }

    /**
     * select all by queryWrapper
     *
     * @param queryWrapper
     * @return
     */
    @Override
    public Result<TmptBaseFileBizDto> selectBy(QueryWrapper<TmptBaseFileBiz> queryWrapper) {
        return super.selectBy(queryWrapper);
    }

    /**
     * select one by id
     *
     * @param id
     * @return
     */
    @Override
    public Result<TmptBaseFileBizDto> selectById(Long id) {
        return super.selectById(id);
    }


    // ==================================================================================
    // ========== 以下使用的是自定义的 mapper.xml 实现, 适合多表查询 =========================
    // ==================================================================================

    /**
     * 分页查询：mybatis plus 自定义sql分页查询
     * 默认开启合计查询，按需注掉代码
     *
     * @param page
     * @param queryWrapper
     * @return
     */
    @Override
    public Result<TmptBaseFileBizDto> myPage(Page<TmptBaseFileBiz> page, QueryWrapper<TmptBaseFileBiz> queryWrapper) {
        return super.myPage(page, queryWrapper);
    }

    @Override
    public Result<TmptBaseFileBizDto> mySelectBy(QueryWrapper<TmptBaseFileBiz> queryWrapper) {
        return super.mySelectBy(queryWrapper);
    }

    @Override
    public Result<TmptBaseFileBizDto> mySelectById(long id) {
        return super.mySelectById(id);
    }

    public static void main(String[] args) {
        LocalDateTime localDateTime = LocalDateTime.now();
        DateTimeFormatter dtf2 = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String strDate2 = dtf2.format(localDateTime.minusDays(30));
        System.out.println(strDate2);
    }

    @Override
    public Result deleteHisFile(Map<String, String> types) {
        //Map<String, String> types = new HashMap<>();
        //types.put("type", "gj-car-big,gj-car-small,gj-person-big,gj-person-small");
        log.info("【清理DFS历史文件】- 要删除的文件来源为:{}", types.get("type"));
        long begin = System.currentTimeMillis();
        String type = types.get("type");
        if (Strings.isNullOrEmpty(type)) {
            return Result.builder().fault("清理DFS历史文件失败，请指定要清理的文件来源!");
        }
        String limit = types.get("limit");
        if (StringUtils.isNull(limit)) {
            limit = "100";
        }
        String minusDays = types.get("minusDays");
        if (StringUtils.isNull(minusDays)) {
            minusDays = "30";
        }
        String[] sourceArray = type.split(",");
        LocalDateTime localDateTime = LocalDateTime.now();
        DateTimeFormatter dtf2 = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        // String strDate2 = dtf2.format(localDateTime.minusMonths(1));
        String strDate2 = dtf2.format(localDateTime.minusDays(Integer.parseInt(minusDays)));
        try {
            //循环国金车、人的大小图，自一个月之前的数据开始倒序进行删除。
            for (String source : sourceArray) {
                QueryWrapper queryWrapper = new QueryWrapper();
                queryWrapper.lt("createdate", strDate2);
                queryWrapper.eq("source", source);
                // queryWrapper.eq("deleteflag", "0");
                queryWrapper.orderByAsc("id"); // wxy 物理删除时，由小到大排序，会不会速度快点
                queryWrapper.last("limit "+limit);
                // wxy
                List<TmptBaseFileBiz> baseFileList = super.tmptBaseFileBizMapper.selectList(queryWrapper);
                if (baseFileList.isEmpty()) continue;
                List<Long> ids = new ArrayList<>(); // wxy 批量删除的id列表
                for(TmptBaseFileBiz baseFileBiz: baseFileList){
                    String url = baseFileBiz.getUrlGroup();
                    try {
                        url = url.substring(url.indexOf("M"));
                        dfsService.deleteFile("group1", url);
                        ids.add(baseFileBiz.getId()); // wxy 批量删除的id列表
                    } catch (Exception e) {
                        log.error("dfserr删除文件时发生错误，url:{},错误信息:{}", url,e.getMessage());
                        // 异常的做标志，人工排查
                        baseFileBiz.setDeleteflag(1);
                        baseFileBiz.setModifydate(DateTool.getCurrentDatetime());
                        super.tmptBaseFileBizMapper.updateById(baseFileBiz);
                    }
                }
                // wxy 先用update来伪删除，生产运行一段时间，正常话，切换成下一句，批量物理删除
                if (ids.isEmpty()) continue;
                super.tmptBaseFileBizMapper.deleteBatchIds(ids);
            }
        }catch (Exception e) {
            log.info("【清理DFS历史文件】- dfserr:", e.getLocalizedMessage());
            return Result.builder().success(e.getLocalizedMessage()+": 本次请求耗时：" + (System.currentTimeMillis() - begin));
        }

        return Result.builder().success("本次请求耗时：" + (System.currentTimeMillis() - begin)+"; types:"+types);
    }

}
